package action;

import java.util.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import db.*;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {

	private User user;
	private String errorinfo="li";
	private UserDAO userDAO;
	private List<User> list;
	
	public List<User> getList() {
		return list;
	}

	public void setList(List<User> list) {
		this.list = list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String execute() {	
		User matchUser;
		System.out.println("here");
		// -- Get the user by "Username"
		userDAO = new UserDAO();
		String username = user.getUsername();
		List<User> userList = userDAO.findByUsername(username);
		if(userList.isEmpty()){
			errorinfo = getText("err.username.null");
			//System.out.println("err.username.null");
			return ERROR;
		}else{//such user exists, check password
			matchUser = userList.get(0);
			if(!matchUser.getUPassword().equals( this.user.getUPassword() )) {
				errorinfo = getText("err.password.wrong");
				//System.out.println("err.password.wrong");
				return ERROR;
			}
			else{
				this.user = matchUser;
				//Get the privilege - "1" for admin, "0" for user.					
				//error = "";
			    Map session = ActionContext.getContext().getSession();
			    String userId = ""+matchUser.getUId();
			    String userfullname = ""+matchUser.getUFullname();
				if(this.user.getURole() == 1) {
					String _admin = "1";
					this.setUser(matchUser);
					session.put("userRole", _admin);
					session.put("userId", userId);
					session.put("userfullname", userfullname);
					return "admin";
				}
				else if(this.user.getURole() == 0) {
					String _user = "0";
					this.setUser(matchUser);
					this.setList(userList);
					System.out.println("-- user");
					System.out.println(matchUser.getUFullname());
					session.put("userRole", _user);
					session.put("userId", userId);
					session.put("userfullname", userfullname);
					return "user";
				}				
			}			
		}		
		return ERROR;		
	}
	
	@SuppressWarnings("unchecked")
	public String logout() {		
		Map session = ActionContext.getContext().getSession(); 
		session.put("userRole", null);
		session.put("userId", "0");	
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	public String getErrorinfo() {
		return errorinfo;
	}

	public void setErrorinfo(String error) {
		this.errorinfo = error;
	}

}

